<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <link rel="stylesheet/less" href="./less/reset.less"/>
    <link rel="stylesheet/less" href="./less/top_up.less"/>
    <link rel="stylesheet" href="https://res.wx.qq.com/open/libs/weui/2.4.4/weui.min.css">
    <script src="https://cdn.bootcdn.net/ajax/libs/less.js/4.1.1/less.min.js"></script>
    <script type="text/javascript" src="https://res.wx.qq.com/open/libs/weuijs/1.2.1/weui.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/qs/6.9.6/qs.js"></script>
    <script src="http://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <title></title>
</head>
<body>
    <div id="app">
        <div class="main">
            <div class="login-top">
                <header class="title">
                    <div class="spell">充值</div>
                    <a href="./myWallet.html">
                        <img src="./img/arrow_back.png">
                    </a>
                </header>
            </div>
            <div class="amount">
                <div>充值金额</div>
                <ul>
                    <li v-for="(item,index) in amount" :class="isActive==index&&isActiveStatus?'select':'default'" @click="tabb(index)">充{{item}}元</li>
                    <li>
                        <input type="number" placeholder="自定义金额" @click="focus()" v-model="customAmount"/>
                    </li>
                </ul>
            </div>
            <div class="payment">
                <div>选择支付方式</div>
                <ul>
                    <li v-for="(item,index) in  payment">
                        <ul>
                            <li>
                                <ul>
                                    <li>
                                        <img :src="item.cardImg">
                                    </li>
                                    <li>{{item.name}}</li>
                                </ul>
                            </li>
                            <li>
                                <img :src="paymentStatus&&isPayMent==index?'./img/right.png':item.choose" @click="select(index)">
                            </li>
                        </ul>
                    </li>
                </ul>
                <div class="recharge" @click="prepaid">立即充值</div>
            </div>
            <div v-if="status">
                <div class="mask"  @click="totas"></div>
                <div class="Popup">
                    <div class="aside">
                        <img src="./img/card_back.png" @click="totas">
                        <div>请选择一张银行卡</div>
                        <div></div>
                    </div>
                    <ul class="scroll">
                        <li v-for="(item,index) in  bankCard">
                            <ul>
                                <li>
                                    <ul>
                                        <li>
                                            <img :src="item.cardImg">
                                        </li>
                                        <li>{{item.name}}</li>
                                    </ul>
                                </li>
                                <li>
                                    <img :src="bankStatus&&selectBankCard==index?'./img/right.png':item.choose" @click="bankCardSelect(index)">
                                </li>
                            </ul>
                        </li>
                        <li>
                            <a href="./addBankCard.html">+添加新银行卡</a>
                        </li>
                    </ul>
                </div>
            </div>
            <div v-if="passwordStatus">
                <div class="mask"  @click="backHandle"></div>
                <div class="pay-tool">
                    <div class="pay-tool-title border-bottom">
                        <img class="icon-back" src="./img/card_back.png" @click="backHandle"/><strong>请输入交易密码</strong>
                    </div>
                    <div class="pay-tool-content">
                        <div class="pay-tool-inputs">
                            <div class="item" v-for="i in items"><span class="icon_dot" v-if="password[i]"></span></div>
                        </div>
                    </div>
                    <div class="pay-tool-keyboard">
                        <ul>
                            <li @click="keyUpHandle($event)" v-for="val in keys">{{ val }}</li>
                            <li class="del" @click="delHandle"><span class="icon-del"><</span></li>
                        </ul>
                    </div>
                </div>
            </div>
            <div id="toast" v-show="totasStatus">
                <div class="weui-mask_transparent"></div>
                <div class="weui-toast">
                    <i class="weui-icon-success-no-circle weui-icon_toast"></i>
                    <p class="weui-toast__content">支付成功</p>
                </div>
            </div>
            <div id="textToast" v-show="tooltip">
                <div class="weui-mask_transparent"></div>
                <div class="weui-toast weui-toast_text">
                    <p class="weui-toast__content">{{tooltipName}}</p>
                </div>
            </div>
            <div id="loadingToast" v-if="loadingStatus">
                <div class="weui-mask"></div>
                <div class="weui-toast">
                    <span class="weui-primary-loading weui-icon_toast">
                      <span class="weui-primary-loading__dot"></span>
                    </span>
                    <p class="weui-toast__content">加载中</p>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
<script type="module">
    import { myBankCardList, myBalance, bankCardPayment, rechargePayment, balancePayment ,getInfoByCode } from './js/request/api.js';
    import { shareLink, getFloatStr } from './js/public.js';
    Vue.prototype.public = {shareLink, getFloatStr};
    const keys = () => [1, 2, 3, 4, 5, 6, 7, 8, 9, '', 0]
    let app = new Vue({
        el: '#app',
        data: {
            api: 'http://mall.fhzhny.com/api',
            status: false,
            isActiveStatus: false,
            amount: [1000,500,300],
            isActive: 0,
            isPayMent: null,
            selectBankCard: null,
            rechargeAmount: 0,
            customAmount: '',
            items: [0, 1, 2, 3, 4, 5],
            keys: keys(),
            password: [],
            payment:[
                {
                    cardImg: './img/bank.png',
                    name: '银行卡支付',
                    choose: './img/choose.png'
                },
                // {
                //     cardImg: './img/Alipay.png',
                //     name: '支付宝支付',
                //     choose: './img/choose.png'
                // },
                {
                    cardImg: './img/weChatPay.png',
                    name: '微信支付',
                    choose: './img/choose.png'
                }
            ],
            isSelectImg: './img/choose.png',
            bankCard:[],
            selectCard:{},
            inputList:[
                {
                    val: ''
                },
                {
                    val: ''
                },
                {
                    val: ''
                },
                {
                    val: ''
                },
                {
                    val: ''
                },
                {
                    val: ''
                }
            ],
            passwordStatus: false,
            tooltip: false,
            totasStatus: false,
            tooltipName: '',
            code: '',
            openid: '',
            loadingStatus: false,
            paymentStatus: false,
            bankStatus: false
        },

        created(){
            let that = this;
                that.getCode();
        },

        mounted(){
            let that = this;
                that.bankCardList();
                that.getOpenId();
                that.public.shareLink();
                that.loadingStatus = true;    
                setInterval(() => {
                    that.loadingStatus = false;
                },2000)  
        },

        methods:{

            tabb(index){
                let that = this;
                    that.isActive = index;
                    that.isActiveStatus = true;
                    that.rechargeAmount = that.amount[index];
                    console.log(that.rechargeAmount);
            },

            select(index){
                let that = this;
                    that.isPayMent = index;
                    that.paymentStatus = true;
                    if(index == 0){
                        that.status = true;
                    }else{
                        that.status = false;
                    }
            },

            bankCardSelect(index){
                let that = this;
                    that.selectBankCard = index;
                    that.bankStatus = true;
                    that.payment[0].name = that.bankCard[index].name;
                    that.selectCard = that.bankCard[index];
            },

            totas(){
                let that = this;
                let status = that.status;
                    this.status = !status;
            },

            focus(){
                let that = this;
                    that.isActiveStatus = false;

            },
            bankCardList(){
                let that = this;
                let userData = JSON.parse(localStorage.getItem("userData"));
                myBankCardList({
                    userId: userData.userId,
                }).then((res)=>{
                let bankCard = res.data.map((item,index)=>{
                    return{
                        cardImg: './img/bank.png',
                        userId: item.userId,
                        name: item.bankName+'('+item.bankAccount.slice(item.bankAccount.length-5,item.bankAccount.length-1)+')',
                        bankCardId: item.bankCardId,
                        choose: './img/choose.png'
                    }
                })
                that.bankCard = bankCard;
                }).catch((error)=>{
                    console.log(error);
                })
            },
            prepaid(){
                let that = this;
                let userData = JSON.parse(localStorage.getItem("userData"));

                if(that.isActiveStatus == false && that.customAmount ==''){
                    that.tooltip = true;
                    that.tooltipName = '请选择充值金额或输入充值金额';
                    setTimeout(()=>{
                        that.tooltip = false;
                    },2000)
                }else if(that.paymentStatus==false){
                    that.tooltip = true;
                    that.tooltipName = '请选择支付方式';
                    setTimeout(()=>{
                        that.tooltip = false;
                    },2000)
                }

                if(that.isPayMent == 0){
                    if(that.bankStatus==false){
                        that.tooltip = true;
                        that.tooltipName = '请选择银行卡';
                        setTimeout(()=>{
                            that.tooltip = false;
                        },2000)
                    }else{
                        that.passwordStatus = true;
                    }

                }else if(that.isPayMent == 1){

                        if(that.isActiveStatus == true){
                            rechargeAmount = that.rechargeAmount;
                        }else{
                            rechargeAmount = that.customAmount;
                        }

                        that.wechatPay(userData.userId);
                }else if(that.isPayMent == 2){

                        if(that.isActiveStatus == true){
                            rechargeAmount = that.rechargeAmount;
                        }else{
                            rechargeAmount = that.customAmount;
                        }
                }
            },

            backHandle () {
                let that = this;
                    that.clearPasswordHandle(); // 返回时清除password
                    that.$emit('backFnc'); // 返回上级
                let passwordStatus = !that.passwordStatus;
                    that.passwordStatus = passwordStatus;
            },

            keyUpHandle (e) {

                let that = this;
                let text = e.currentTarget.innerText;
                let len = that.password.length;
                    if (!text || len >= 6) return
                        that.password.push(text)
                        that.ajaxData();
            },

            delHandle () {
                if (this.password.length <= 0) return false
                this.password.shift()
            },

            ajaxData () {
                let that = this;
                if (that.password.length >= 6) {
                    let password = parseInt(that.password.join(' ').replace(/\s/g, ''));
                    let rechargeAmount;
                    that.clearPasswordHandle(); 
                    if(that.isActiveStatus == true || that.customAmount !=''){

                        if(that.isActiveStatus == true){
                            rechargeAmount = that.rechargeAmount;
                        }else{
                            rechargeAmount = that.customAmount;
                        }

                        if(that.isPayMent == 0){
                            bankCardPayment({
                                userId: that.selectCard.userId,
                                orderAmount: that.public.getFloatStr(that.price),
                                bankCardId: that.selectCard.bankCardId,
                                payPwd: password
                            }).then(res=>{
                                if(res.code != 0){
                                    that.clearPasswordHandle();
                                    that.tooltip = true;
                                    that.tooltipName = res.data.msg;  
                                    setTimeout(()=>{
                                        that.tooltip = false;
                                    },2000)
                                }else if(res.code == 0){
                                    that.clearPasswordHandle();
                                    that.totasStatus = true;
                                    setTimeout(()=>{
                                        that.totasStatus = false;
                                        let url = './myWallet.html';
                                            window.location.href = url;
                                    },2000)
                                }
                            }).catch(error=>{
                                console.log(error);
                            })
                        }
                    }
                    that.passwordStatus = false;
                }
                return false
            },

            clearPasswordHandle: function () {
                this.password = []
            },

            getCode() { // 非静默授权，第一次有弹框
                let that = this;
                let code = '';
                let appid = 'wx65072cc8cc20238e';
                let local = window.location.href;
                    code = this.getUrlCode().code; // 截取code
                    that.code = code;

                let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_base&state=state`;
                if (this.code == null || this.code === '') { // 如果没有code，则去请求
                    localStorage.setItem('url',JSON.stringify(url));
                    window.location.href = url;
                } else {
                    // 你自己的业务逻辑
                    console.log(123);
                }
            },

            getUrlCode() { // 截取url中的code方法
                var url = location.search
                this.winUrl = url
                var theRequest = new Object()
                if (url.indexOf("?") != -1) {
                    var str = url.substr(1)
                    var strs = str.split("&")
                    for(var i = 0; i < strs.length; i ++) {
                        theRequest[strs[i].split("=")[0]]=(strs[i].split("=")[1])
                    }
                }
                return theRequest
            },

            getOpenId(){
                let that = this;
                getInfoByCode({
                    code: that.code
                }).then((res)=>{
                    that.openid = res.data.openid;
                }).catch((error)=>{
                    console.log(error);
                })
            },

            Alipay(userId){
                let that = this;
                rechargePayment({
                    userId: userId,
                    payType: 1,
                    balance: that.public.getFloatStr(that.price),
                }).then(function (res) {
                    if(res.code == 101){
                        that.tooltip = true;
                        that.tooltipName = res.data.msg;  
                        setTimeout(()=>{
                            that.tooltip = false;
                        },2000)
                    }
                })
                .catch(function (error) {
                    console.log(error);
                });
            },

            wechatPay(userId){

                let that = this;

                rechargePayment({
                    userId: userId,
                    payType: 2,
                    balance: that.public.getFloatStr(that.price),
                    openid: that.openid
                }).then(res=>{
                    let data = res.data;

                    function onBridgeReady(){

                        WeixinJSBridge.invoke(
                            'getBrandWCPayRequest', {
                                "appId": data.appId,
                                "timeStamp": data.timeStamp,         
                                "nonceStr": data.nonceStr, 
                                "package": data.package,     
                                "signType": "MD5",            
                                "paySign":  data.paySign 
                            },(res)=>{
                            if(res.err_msg == "get_brand_wcpay_request:ok" ){
                                let url = './myWallet.html';
                                    window.location.href = url;
                            } 
                        }); 
                    }

                    if (typeof WeixinJSBridge == "undefined"){
                        if( document.addEventListener ){
                            document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                            }else if (document.attachEvent){
                                document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
                                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                            }
                            }else{
                        onBridgeReady();
                    }
                }).catch(error=>{
                    console.log(error);
                })
            },
    },
})
</script>
